<?php

namespace app\middleware;

use tools\MyHelp;

class Sign
{
    /**
     * @param int $type 0无需验证apid
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next, $type = 0)
    {
        $data = $param = $request->param();
        $route = $request->route();
        $keys = array_keys($route);
        $keys[] = 'sign';
        $type = $type == 1 && array_key_exists('apid', $data) ? 0 : $type;
        foreach ($keys as $v) {
            if (array_key_exists($v, $param)) {
                unset($param[$v]);
            }
        }
        $a = new \app\validate\Sign();
        switch ($type) {
            case 0:
                $a = $a->scene('public');
                break;
            case 1:
                $a = $a->scene('private');
                break;
        }
        $result = $a->check($data);
        if (!$result) {
            return json([
                'code' => 1002,
                'msg' => $a->getError()
            ]);
        }
        $help = new MyHelp();
        if (!$help->chackSign($data, $param, $type)) {
            return json($help->getError());
        };
        $request->data = $param;
        return $next($request);
    }
}
